package kamikaze.service.product;

import java.util.List;

import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;

import kamikaze.entity.Feedback;
import kamikaze.entity.Product;
import kamikaze.support.HttpMethod;
import kamikaze.support.Service;
import kamikaze.support.ServiceConfig;
import kamikaze.support.ServiceContext;
import kamikaze.support.ServiceException;

@ServiceConfig(path = "product/detail", method = HttpMethod.GET)
public class DetailProductService implements Service {

	@Override
	public String serve(ServiceContext ctx) throws Exception {
		HttpServletRequest req = ctx.getRequest();
		
		final String id = req.getParameter("id");
		if (id != null && !id.isEmpty()) {

			Query q1 = ctx.getEntityManager().createQuery(
					"Select p from Product p where p.productId= :productId");
			q1.setParameter("productId", Long.valueOf(id));
			Product product = (Product) q1.getSingleResult();									
			req.setAttribute("product", product);
			
			Query q2 = ctx.getEntityManager().createQuery(
					"Select f from Feedback f where f.productId= :productId");
			q2.setParameter("productId", Long.valueOf(id));			
			List<Feedback> feedbackList = q2.getResultList();
			req.setAttribute("feedbackList", feedbackList);
			
			return "product/detail";

		} else {
			throw new ServiceException("Product ID is unknown.");
		}
	}

}
